<template>
  <p style="text-align: center; margin: 0 0 20px">
    Update accident related items
  </p>
  <div class="transfer" style="text-align: center">
    <el-transfer
      v-model="rightValue"
      style="
        width: 1000px;
        height: 500px;
        text-align: left;
        display: inline-block;
      "
      filterable
      :render-content="renderFunc"
      :titles="['Source', 'Target']"
      :button-texts="['', '']"
      :format="{
        noChecked: '${total}',
        hasChecked: '${checked}/${total}',
      }"
      :data="data"
      @change="handleChange"
    >
      <!-- <template #left-footer>
        <el-button class="transfer-footer" size="small">Operation</el-button>
      </template> -->
      <!-- <template #right-footer>
        <el-button style="margin-left: 4px" type="primary" size="medium"
          >Update</el-button
        >
      </template> -->
    </el-transfer>
    <footer class="footer">
      <div>
        <el-button class="cancel" size="default" @click="close"
          >Close</el-button
        >
        <el-button type="primary" size="default" @click="update"
          >Update</el-button
        >
      </div>
    </footer>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed, defineProps, watch, defineEmits } from "vue";
import type {
  TransferDirection,
  TransferKey,
  renderContent,
} from "element-plus";
import api from "@/utils/axiosInstance";
import { ElMessage } from "element-plus";

interface Option {
  key: string;
  label: string;
  disabled: boolean;
}

const data = ref<Option[]>([]);
const rightValue = ref<string[]>([]); // 右侧选中的值，初始为空

// receive value

const props = defineProps({
  //子组件接收父组件传递过来的值
  row: Object,
  itemType: String,
});
//使用父组件传递过来的值
const accident_id = computed(() => props.row.Id);
const item_type = computed(() => props.itemType);

// 组件挂载时检查row是否存在，若存在则请求数据
onMounted(() => {
  if (props.row) {
    fetchData();
  }
});

// 监听visible变化，当变为true时请求数据
watch(
  () => (props.row, props.itemType),
  async (newVal1, newVal2) => {
    if (newVal1) {
      await fetchData();
    }
    if (newVal2) {
      await fetchData();
    }
  }
);

const fetchData = async () => {
  try {
    let responseData = [];
    if (item_type.value == "1") {
      const chemicalResponse = await api.post("/chemical/select");
      responseData = chemicalResponse.data || [];
    } else if (item_type.value == "2") {
      const equipmentResponse = await api.post("/equipment/select");
      responseData = equipmentResponse.data || [];
    } else if (item_type.value == "3") {
      const consumableResponse = await api.post("/consumable/select");
      responseData = consumableResponse.data || [];
    }
    // 转换数据格式并赋值给组件的data引用
    data.value = responseData.map((item) => ({
      key: item.Id.toString(), // 确保key为字符串类型
      label: `${item.Name}--${item.DictName}`,
      disabled: false,
    }));

    const relatedItems = await api.post("/accident/item-all", {
      accident_id: accident_id.value,
      item_type: item_type.value,
    });
    let nowValue = [];
    for (var i = 0; i < relatedItems.data.length; i++) {
      nowValue.push(relatedItems.data[i].Id);
    }

    rightValue.value = nowValue; // 示例：默认选中key为1和2的项
  } catch (error) {
    console.error("加载数据失败:", error);
    // 可以添加错误提示
  } finally {
  }
};

const renderFunc: renderContent = (h, option) => h("span", null, option.label);

const handleChange = (
  value: TransferKey[],
  direction: TransferDirection,
  movedKeys: TransferKey[]
) => {
  console.log("值变化:", value, "方向:", direction, "移动的键:", movedKeys);
};

const emit = defineEmits(["close"]);
// 关闭方法：触发close事件
function close() {
  emit("close");
}

function update() {
  api
    .post("/accident/update-related-item", {
      accident_id: accident_id.value,
      item_type: item_type.value,
      items: rightValue.value,
    })
    .then((response) => {
      if (response.status == 200) {
        ElMessage({
          message: "Update Successfully!",
          type: "success",
        });
      }
    })
    .catch((error) => {
      // 处理错误
      console.log(error, "error");
    })
    .finally(() => {
      close();
    });
}
</script>

<style scoped>
.transfer-footer {
  margin-left: 6px;
  padding: 6px 5px;
}
.transfer >>> .el-transfer-panel {
  width: 350px;
}
.el-transfer {
  --el-transfer-panel-width: 350px;
  --el-transfer-panel-body-height: 420px;
}
.footer {
  margin: 8px 8px 0 0;
  display: flex;
  justify-content: space-between;
}
</style>
